package com.atxiao.service.JUC.Lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//可重入锁实现卖票
class Ticket{
    private int number=100;
    Lock lock=new ReentrantLock();


    public void saleTicket(){
        try {
            //加锁
            lock.lock();
            if (number>0){
                System.out.println(Thread.currentThread().getName()+"卖出了第"+(number--)+"张票，还剩下"+number+"张票");
            }
        }finally {
            //解锁
            lock.unlock();
        }
    }

}

public class LockTicket {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                ticket.saleTicket();
            }
        },"AA").start();

        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                ticket.saleTicket();
            }
        },"BB").start();


        new Thread(()->{
            ticket.saleTicket();
        },"CC").start();
    }




}
